package com.ytsakura.blog.web;

import com.ytsakura.blog.pojo.Blog;
import com.ytsakura.blog.pojo.Tag;
import com.ytsakura.blog.pojo.Type;
import com.ytsakura.blog.pojo.User;
import com.ytsakura.blog.service.BlogService;
import com.ytsakura.blog.service.TagService;
import com.ytsakura.blog.service.TypeService;
import com.ytsakura.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/login")
    public String getLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String postLogin(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user=userService.checkUser(username,password);
        if(user!=null){
            user.setPassword(null);
            session.setAttribute("user",user);
            session.setAttribute("loginStatus",true);
            if (user.getType() == 2) {
                return "redirect:/admin/index";
            }else {
                return "redirect:/";
            }
        }else{
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.setAttribute("loginStatus",false);
        session.removeAttribute("user");
        return "redirect:/";
    }

    @GetMapping("/register")
    public String getRegister(){
        return "register";
    }

    @PostMapping("/register")
    public String postRegister(User user,RedirectAttributes attributes){
        user.setAvatar("/images/avatar.png");
        //user.setAvatar("https://i.picsum.photos/id/866/200/200.jpg");
        User u = null;
        if(userService.getUser(user.getUsername()) == null){
            u = userService.saveUser(user);
        }
        if (u == null){
            attributes.addFlashAttribute("message","注册失败");
            return "redirect:/register";
        }else{
            attributes.addFlashAttribute("message","注册成功");
            return "redirect:/login";
        }
    }

    @GetMapping("/blog-m")
    public String myBlog(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                         HttpSession session,RedirectAttributes attributes, Model model){
        if (session.getAttribute("user") == null){
            attributes.addFlashAttribute("message","请先登录");
            return "redirect:/login";
        }else{
            User user = (User) session.getAttribute("user");
            model.addAttribute("page",blogService.listBlogByUser(pageable,user));
        }
        return "blog-m";
    }

    @PostMapping("/blog-m")
    public String post(Blog blog, RedirectAttributes attributes, HttpSession session){
        blog.setUser((User)session.getAttribute("user"));
        if (blog.isPublished()) {
            blog.setTags(tagService.listTag(blog.getTagIds()));
        }
        Blog b;
        if (blog.getId() == null){
            b = blogService.saveBlog(blog);
        }else {
            b = blogService.updateBlog(blog.getId(),blog);
        }

        if (b == null){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/blog-m";
    }

    @PostMapping("/blog-m/search")
    public String mySearch(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                           Model model, @RequestParam String str,HttpSession session){
        User user = (User)session.getAttribute("user");
        model.addAttribute("page",blogService.listBlogByUser(pageable,user,"%"+str+"%"));
        model.addAttribute("str",str);
        return "blog-m";
    }

    private void setTypeAndTag(Model model) {
        model.addAttribute("tags", tagService.listTag());
        model.addAttribute("types", typeService.listType());
    }

    @GetMapping("/blog-m/input")
    public String myInput(Model model){
        setTypeAndTag(model);
        model.addAttribute("blog",new Blog());
        return "myInput";
    }

    @GetMapping("/blog-m/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        setTypeAndTag(model);
        Blog blog = blogService.getBlog(id);
        blog.init();
        model.addAttribute("blog",blog);
        return "myInput";
    }

    @GetMapping("/blog-m/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/blog-m";
    }

    @GetMapping("/about")
    public String about(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                        HttpSession session,RedirectAttributes attributes, Model model){
        if (session.getAttribute("user") == null){
            attributes.addFlashAttribute("message","请先登录");
            return "redirect:/login";
        }else{
            User user = (User) session.getAttribute("user");
            List<Blog> blogs = blogService.listBlogByUser(pageable,user).getContent();
            List<Tag> tags = new ArrayList<>();
            List<Type> types = new ArrayList<>();
            for(Blog b : blogs){
                if(!types.contains(b.getType())){
                    types.add(b.getType());
                }
            }
            for(Blog b : blogs){
                for (Tag t : b.getTags()){
                    if(!tags.contains(t)){
                        tags.add(t);
                    }
                }
            }
            model.addAttribute("avatar",user.getAvatar());
            model.addAttribute("types",types);
            model.addAttribute("tags",tags);
            model.addAttribute("blogCount",userService.getUser(user.getUsername()).getBlogs().size());
            model.addAttribute("page",blogService.listBlogByUser(pageable,user));
        }
        return "about";
    }

    @PostMapping("/about/search")
    public String search(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                           Model model, @RequestParam String find,HttpSession session){
        User user = (User)session.getAttribute("user");
        model.addAttribute("page",blogService.listBlogByUser(pageable,user,"%"+find+"%"));
        model.addAttribute("find",find);
        return "about";
    }

    @GetMapping("/myInfo")
    public String showMyInfo(HttpSession session,Model model){
        model.addAttribute("user",session.getAttribute("user"));
        return "myInfo";
    }

    @PostMapping("/myInfo")
    public String postMyInfo(HttpSession session,User user,RedirectAttributes attributes){
        int flag = 0;
        User u = (User)session.getAttribute("user");
        System.out.println(user.getPassword());
        if (user.getPassword().equals("")){
            user.setPassword(null);
        }else {
            //user.setPassword(MD5Utils.code(user.getPassword()));
            user.setPassword(user.getPassword());
            flag = 1;
        }
        User u1 = userService.updateUser(u.getId(),user);
        if (u1 == null){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            if (flag == 1){
                attributes.addFlashAttribute("message","密码修改成功,请重新登录");
                return "redirect:/login";
            }
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/myInfo";
    }
}
